﻿using System;
using System.Data;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;

using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
	public sealed class GetCouponCommandHandler : BaseCommandHandler, IRequestHandler<GetCouponCommand, BaseResult<string>>
	{
		private readonly IMemberRepository _memberRepository;
		private readonly IMemberCouponRepository _memberCouponRepository;
		private readonly IMemberCouponGiveRepository _memberCouponGiveRepository;
		private readonly ICasaMielSession _session;
		private readonly IMemcachedClient _memcachedClient;
		private readonly string _memcachedPrex;
		/// <summary>
		///
		/// 领券
		/// </summary>
		/// <param name="memberRepository"></param>
		/// <param name="memberCouponRepositor"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		/// <param name="casaMielSession"></param>
		/// <param name="memberCouponGiveRepository"></param>
		/// <param name="memcachedClient"></param>
		public GetCouponCommandHandler(IMemberRepository memberRepository, IMemberCouponRepository memberCouponRepositor, INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings, ICasaMielSession casaMielSession, IMemberCouponGiveRepository
			memberCouponGiveRepository, IMemcachedClient memcachedClient) : base(netICService, httpClientFactory, settings)

		{
			_memberRepository = memberRepository;
			_memberCouponRepository = memberCouponRepositor;
			_session = casaMielSession;
			_memberCouponGiveRepository = memberCouponGiveRepository;
			_memcachedClient = memcachedClient;
			_memcachedPrex = settings.Value.MemcachedPre;
		}

		public async Task<BaseResult<string>> Handle(GetCouponCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			var coupongive = await _memberCouponGiveRepository.FindAsync<ICasaMielSession>(request.ForwardCode).ConfigureAwait(false);
			if (coupongive == null) {
				return new BaseResult<string>("", 9999, "赠券信息不存在");
			}
			if (coupongive.Status == -1) {
				return new BaseResult<string>("", 9999, "赠券信息已过期");
			}
			if (coupongive.Status == 1) {
				return new BaseResult<string>("", 9999, "券已被领取");
			}
			var couponinfo = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(coupongive.MCID).ConfigureAwait(false);
			if (couponinfo == null) {

				return new BaseResult<string>("", 9999, "券信息有误");

			}
			var _cachekey = _memcachedPrex + Constant.GETCOUPON + couponinfo.Ticketcode;

			var trynum = _memcachedClient.Increment(_cachekey, 1, 1);

			if (trynum > 1) {

				var coupongive1 = await _memberCouponGiveRepository.FindAsync<ICasaMielSession>(request.ForwardCode).ConfigureAwait(false);
				if (coupongive1 == null) {
					return new BaseResult<string>("", 9999, "赠券信息不存在");
				}
				if (coupongive1.Status == -1) {
					return new BaseResult<string>("", 9999, "赠券信息已过期");
				}
				if (coupongive1.Status == 1) {
					return new BaseResult<string>("", 0, "领取成功");
				}
			}
			var member = await _memberRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);


			if (member == null) {
				member = new Domain.Entity.Member {
					Mobile = request.Mobile,
					CreateDate = DateTime.Now
				};
				await _memberRepository.SaveAsync<ICasaMielSession>(member).ConfigureAwait(false);
			}
			coupongive.Mobile = request.Mobile;
			coupongive.LastTime = DateTime.Now;
			coupongive.Status = 1;
			ICResult IcRsp;
			try {
				IcRsp = await NetICService.Tmticketchange(new Domain.Request.TmticketchangeRequest {
					Ticketcode = couponinfo.Ticketcode
				}).ConfigureAwait(false);
				if (IcRsp.code != 0) {
					_memcachedClient.Remove(_cachekey);
					return new BaseResult<string>("", IcRsp.code, IcRsp.msg);
				}
			} catch (Exception) {
				_memcachedClient.Remove(_cachekey);
				throw;
			}


			var d = JObject.Parse(IcRsp.content);
			var memberCoupon = new MemberCoupon {
				CreateTime = DateTime.Now,
				GiveStatus = 1,
				Productname = couponinfo.Productname,
				OldTicketcode = couponinfo.Ticketcode,
				Price = couponinfo.Price,
				Productid = couponinfo.Productid,
				Enddate = couponinfo.Enddate,
				Startdate = couponinfo.Startdate,
				State = couponinfo.State,
				Ticketcode = d["newticketcode"].ToString()

			};

			bool s = false;
			try {
				using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
					await _memberCouponGiveRepository.UpdateAsync(coupongive, uow).ConfigureAwait(false);
					s = await _memberCouponRepository.UpdateCouponGiveStatusAsnync(couponinfo, 2, uow).ConfigureAwait(false);
					if (member == null) {
						member = new Domain.Entity.Member {
							Mobile = request.Mobile,
							CreateDate = DateTime.Now
						};
						await _memberRepository.SaveAsync(member, uow).ConfigureAwait(false);
					}
					memberCoupon.MID = member.ID;

					await _memberCouponGiveRepository.UpdateAsync(coupongive.MCID, 2, uow).ConfigureAwait(false);
					await _memberCouponRepository.SaveAsync(memberCoupon, uow).ConfigureAwait(false);
					if (s) {
						uow.Commit();
					} else {
						uow.Rollback();
					}

				}
			} catch (Exception ex) {
				_memcachedClient.Remove(_cachekey);
				LoggerSystemErrorInfo.Error($"{ex.StackTrace}");
				return new BaseResult<string>("", 9999, "领优惠券出错了");
			}

			if (s) {
				return new BaseResult<string>("", 0, "领取成功");
			} else {
				_memcachedClient.Remove(_cachekey);
				return new BaseResult<string>("", 0, "请重试");
			}
		}
	}
}
